package com.coocaa.ops.common.tool.http;

import com.alibaba.fastjson.JSON;
import com.coocaa.ops.common.tool.base.InstanceUtil;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author bijiahao
 * @date : 2019/6/27.
 * @description
 */
@Slf4j
public class OkHttpUtil {

    private final OkHttpClient delegate;
    private int socketTimeout = 5000;
    private int connectTimeout = 5000;

    public OkHttpUtil() {
        this.delegate = new OkHttpClient();
    }


    public OkHttpUtil(int socketTimeout, int connectTimeout) {
        this.socketTimeout = socketTimeout;
        this.connectTimeout = connectTimeout;
        this.delegate = new OkHttpClient();
    }

    public String requestGetUrlToJSON(String httpUrl, Map<String, String> paramMap, Map<String, String> headMap) throws IOException {
        httpUrl = this.setParams(httpUrl, paramMap);
        Request.Builder builder = new Request.Builder()
                .url(httpUrl);
        setHeads(builder, headMap);
        Request request = builder.get().build();
        return doRequest(httpUrl, request);
    }

    public String requestGetUrlToJSON(String httpUrl, Map<String, String> paramMap) throws IOException{
        return requestGetUrlToJSON(httpUrl, paramMap, null);
    }


    public String requestPostUrlToJSON(String httpUrl, Object data, Map<String, String> headMap) throws IOException{
        Request.Builder builder = new Request.Builder()
                .url(httpUrl);
        this.setHeads(builder, headMap);
        if (null != data){
            MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
            RequestBody formBody = RequestBody.create(mediaType, JSON.toJSONString(data));
            builder.post(formBody);
        }
        Request request = builder.build();
        return doRequest(httpUrl, request);
    }

    /*************** ===私有方法=== ********************* ===start=== ***************************************/


    private String doRequest(String httpUrl, Request request) throws IOException {
        this.delegate.newBuilder()
                .readTimeout(socketTimeout, TimeUnit.MILLISECONDS)
                .connectTimeout(connectTimeout, TimeUnit.MILLISECONDS)
                .build();
        try {
            Response execute = this.delegate.newCall(request).execute();
            String result = execute.body() != null ? execute.body().string() : "";
            if (execute.isSuccessful()) {
                return result;
            }
        } catch (IOException e) {
            log.error("请求发生IO异常！原因：" + e.getMessage() + "  请求URL:" + httpUrl, e);
            throw e;
        } finally {
            if (null != delegate){
                this.delegate.dispatcher().executorService().shutdown();
                this.delegate.connectionPool().evictAll();
            }
        }
        return null;
    }

    private void setHeads(Request.Builder builder, Map<String, String> headMap) {
        if (headMap != null && !headMap.isEmpty()) {
            for (Map.Entry<String, String> entry : headMap.entrySet()) {
                builder.addHeader(entry.getKey(), entry.getValue());
            }
        }
    }

    private String setParams(String httpUrl, Map<String, String> params) {
        if (params == null || params.isEmpty()) {
            return httpUrl;
        }
        StringBuilder sb = new StringBuilder();
        sb.append(httpUrl);
        if (!httpUrl.contains("?")) {
            sb.append("?");
        }
        for (Map.Entry<String, String> entry : params.entrySet()) {
            sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
        }
        return sb.deleteCharAt(sb.length() - 1).toString();
    }

    public static void main(String[] args) throws Exception{
        String url = "http://115.28.224.134:9000/api/Skyworth/GetArt";
        Map<String, String> params = InstanceUtil.newHashMap();
        params.put("app_key", "2FE02C90608D4C83");
        params.put("sdata", "2020-10-11");
        params.put("edata", "2020-10-30");
        OkHttpUtil okHttpUtil = new OkHttpUtil();
        String res = okHttpUtil.requestGetUrlToJSON(url, params, null);
        System.out.println(res);
    }

}
